from django.http import HttpResponse
from reviews.models import Dish, DishImage
from reviews.serialization_helpers import *
from tagging.models import Tag


def get_feed(request, dish_id):
    try:
        feed_items = Rank.objects.filter(dish__id__exact=dish_id).order_by('modified_date')
        # sorted(user_ranking.rank_set.all(), key=lambda rank: rank.rank)        
        return HttpResponse(serialize_ranks(feed_items), mimetype='application/javascript')
    except:
        return HttpResponse('')

def get_my_ranks(request, tag_id):
    try:
        ranks = Rank.objects.filter(ranking__tag__id__exact=tag_id)
        # myTag = Tag.objects.get(id=tag_id)
        # user_ranking = Ranking.objects.get(tag=myTag, user=request.user)
        # sorted(user_ranking.rank_set.all(), key=lambda rank: rank.rank)
        # ranks = sorted(user_ranking.rank_set.all(), key=lambda rank: rank.rank, reverse=True)
        return HttpResponse(serialize_ranks(ranks), mimetype='application/javascript')
    except:
        return HttpResponse('')

def delete_rank(request, tag_id, dish_id):
    try:
        print tag_id
        print request.user
        print dish_id
        try:
            ranking = Ranking.objects.get(tag__id__exact=tag_id, user__exact=request.user)
            # print 'after ranking'
            rank = Rank.objects.get(ranking__tag__id__exact=tag_id, ranking__user__exact=request.user,
                dish__id__exact=dish_id)
            # print 'after rank'
            rank.delete()
            if len(ranking.rank_set.all()) == 0:
                ranking.delete()
            return HttpResponse('Success')
        except:
            return HttpResponse('Rank does not exist')
    except DoesNotExist:
        return HttpResponse('Something went wrong...')

def get_dishes_for_tag(request, tag_id):
    dishes = Dish.objects.filter(id=1)
    # orankings = Ranking.objects.filter(tag__id__exact=tag_id, user__username="kokoomi")[0]
    # sort orankings by rank, get dishes
    # dishes = [r.dish for r in sorted(orankings.rank_set.all(), key=lambda rank: rank.rank, reverse=False)]

    return HttpResponse(serialize_dishes(dishes, request.user), mimetype='application/javascript')

def get_dish_photo_urls(request, dish_id):
    try:
        photos = DishImage.objects.filter(dish__id__exact=dish_id)
        return HttpResponse(serialize_dish_photos_urls(photos), mimetype='application/javascript')
    except:
        return HttpResponse('')